import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/widgets/BGSinglePlayer.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordsGradesResult.dart';
import 'package:ichinesereader/models/common/StatusMessageResult.dart';
import 'package:ichinesereader/service/assessment.dart';
import 'package:ichinesereader/utils/log.dart';

class TeacherIBSpeakingController extends GetxController {
  RxInt stepTop = (-1).obs;
  AssessmentResult? assessmentResult;
  ExamIbRecord? recordsGrades;
  bool isCompleted = true;
  Map<String, dynamic> selectorMap = {};
  bool isSingleView = false;

  final AssessmentServiceProvider _service = AssessmentServiceProvider();

  void nextPage() {
    if (stepTop < 1) {
      stepTop++;
    } else {
      Get.back();
    }
  }

  void prevPage() {
    stepTop--;
  }

  Future<void> submitPageData() async {
    EasyLoading.show();
    try {
      ExamRunningRecord dto = ExamRunningRecord();

      dto.assessmentId = recordsGrades!.assessmentId;
      dto.questionRecordId = recordsGrades!.questionRecordId;
      dto.userName = recordsGrades!.userName;

      String oralJson = json.encode(selectorMap);
      dto.oralJson = oralJson;

      if (stepTop > 0) {
        dto.submit = true;
      }
      Map jsonList = dto.toJson()..removeWhere((key, value) => value == null);
      String dtoJson = json.encode(jsonList);
      var result = await _service.submitAssessmentGrade(dtoJson);
      if (result.statusCode == 200) {
        var status = statusMessageResultFromJson(result.bodyString);
        if (status.status == 1000) {
          nextPage();
        }
      }
    } catch (e) {
      Log.debug(e);
    } finally {
      Future.delayed(const Duration(milliseconds: 500), () {
        EasyLoading.dismiss();
      });
    }
  }

  Future<void> getAssessmentByStudentName(
      String assessmentId, String studentName, String questionRecordId) async {
    EasyLoading.show();
    try {
      var result =
          await _service.getAssessmentByStudentName(assessmentId, studentName);
      assessmentResult = result;
      getAssessmentGrade(questionRecordId);
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<void> getAssessmentGrade(String questionRecordId) async {
    EasyLoading.show();
    try {
      var response = await _service.getAssessmentGrade(questionRecordId);
      if (response.statusCode == 200) {
        AssessmentRecordsGradesResult data =
            AssessmentRecordsGradesResult.fromJson(
                json.decode(response.bodyString));
        if (data.result != null) {
          recordsGrades = data.result!.examIbRecord;
          if (recordsGrades?.oralJson != null &&
              recordsGrades?.oralJson != '' &&
              recordsGrades?.oralJson != 'null') {
            String oralStr = recordsGrades!.oralJson!;
            Map<String, dynamic> oralDic = json.decode(oralStr);
            oralDic.forEach((key, value) {
              selectorMap[key] = value;
            });
          }
          if (assessmentResult!.list![0].questions!.length == 1) {
            isSingleView = true;
            stepTop.value = 1;
          } else {
            nextPage();
          }
        }
      }
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
  }

  @override
  void onClose() {
    BGSinglePlayer().stop();
    super.onClose();
  }
}
